package control.authcore.impl;

import base.standard.constant.ErrorCode;
import base.standard.constant.ThreadLocalParams;
import base.standard.exception.SimpleException;
import control.authcore.IAuthData;
import control.module.vo.usermanage.UserAuthVo;
import control.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Auth data
 *
 * @description: 提供roles和auths实现
 *               这个类需要在上下文变量中加入LoginId(必须),AuthMessage(可选)
 * @author: cyj
 * @date 2020 -10-22 18:10:09
 */
@Service
public class AuthData implements IAuthData {

    /**
     * User service
     */
    @Autowired
    private IUserService userService;

    @Override
    public List<String> offerAuths() {
        UserAuthVo userAuthVo = Optional.ofNullable(userService.getAuth(ThreadLocalParams.getLoginId()))
                .orElseThrow(() ->
                        new SimpleException(ErrorCode.PERMISSION_DENIED_AUTH, ThreadLocalParams.getAuthMessage()));
        List<String> auths = new ArrayList<>();
        userAuthVo.getRoles().stream().forEach(userRole -> {
            userRole.getAuth().stream().forEach(userAuth -> auths.add(userAuth.getAuth()));
        });
        return auths;
    }

    @Override
    public List<String> offerRoles() {
        UserAuthVo userAuthVo = Optional.ofNullable(userService.getAuth(ThreadLocalParams.getLoginId()))
                .orElseThrow(() ->
                        new SimpleException(ErrorCode.PERMISSION_DENIED_ROLE, ThreadLocalParams.getAuthMessage()));
        List<String> roles = userAuthVo.getRoles().stream().map(userRole -> userRole.getRoleName())
                .collect(Collectors.toList());
        return roles;
    }

}
